package com.yfp.operation.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.MachineDO;
import com.yfp.operation.domain.dto.MarketInfoDTO;
import com.yfp.operation.domain.vo.OrderMarketVO;
import com.yfp.operation.domain.vo.SaleMarketInfoVO;
import com.yfp.operation.domain.vo.TransactionVO;
import com.yfp.operation.domain.vo.WeekMarketVO;
import com.yfp.operation.service.MachineClientLivenessService;
import com.yfp.operation.service.MachineService;
import com.yfp.operation.service.MarketService;
import com.yfp.operation.service.OrderListService;
import com.yfp.operation.utils.DateUtils;
import com.yfp.system.api.domain.SysRole;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 
 * @version 1.0
 * @date 2024-05-27 17:37
 */
@Service
@Slf4j
public class MarketServiceImpl implements MarketService {

    @Resource
    private OrderListService orderListService;
    @Resource
    private MachineClientLivenessService machineClientLivenessService;
    @Resource
    private MachineService machineService;

    /**
     * 交易数据-统计销售接口（维度本月、本周、日）
     * @return
     */
    @Override
    public TransactionVO dealInfo() {

        List<String> machineIds = getAllMachineIds();
        TransactionVO transactionVO = new TransactionVO();
        if (machineIds.isEmpty()) {
            return transactionVO;
        }

        // 获取本月销售情况
        SaleMarketInfoVO monthInfo = orderListService.getMonthInfo(machineIds);
        // 获取本周销售情况
        SaleMarketInfoVO weekInfo = orderListService.getWeekInfo(machineIds);
        // 获取当日销售情况
        SaleMarketInfoVO dayInfo = orderListService.getDayInfo(machineIds);
        transactionVO.setMonthInfo(monthInfo);
        transactionVO.setWeekInfo(weekInfo);
        transactionVO.setDayInfo(dayInfo);
        return transactionVO;
    }

    /**
     * 获取每月销售情况
     * @return
     */
    @Override
    public List<SaleMarketInfoVO> monthlyMarket() {
        List<String> machineIds = getAllMachineIds();
        if (machineIds.isEmpty()) {
            return new ArrayList<SaleMarketInfoVO>();
        }
        // 月销售情况
        List<SaleMarketInfoVO> infoVOList = orderListService.saleMonthInfo(machineIds);
        return infoVOList;
    }

    /**
     * 每周活跃度
     * @return
     */
    @Override
    public List<WeekMarketVO> liveness() {
        List<String> machineIds = getAllMachineIds();
//        ArrayList<String> machineIds = new ArrayList<>();
//        machineIds.add("24083002000009");
        List<WeekMarketVO> weekMarketVOS = new ArrayList<>();
        if (machineIds.isEmpty()) {
            return weekMarketVOS;
        }


        HashMap<Integer, WeekMarketVO> map = new HashMap<>();
        HashSet<Integer> naturalWeeksInMonth = DateUtils.getNaturalWeeksInMonth();
        for (int i1 = 1; i1 < (naturalWeeksInMonth.size() + 1); i1++) {
            WeekMarketVO weekMarketVO = new WeekMarketVO();
            weekMarketVO.setMarketCount(0);
            weekMarketVO.setWeek(i1);
            map.put(i1, weekMarketVO);
        }


        // 获取本月所有活跃度的时间
        List<Date> list = machineClientLivenessService.getDays(machineIds);
        if (!list.isEmpty()) {
            for (Date tian : list) {
                // 本月第几周
                int result = DateUtils.getWhichWeek(DateUtils.convertToLocalDate(tian));
                // 如果包含该周数，则活跃度+1
                if (map.containsKey(result)) {
                    WeekMarketVO weekMarketVO = map.get(result);
                    weekMarketVO.setMarketCount(weekMarketVO.getMarketCount() +1);
                }
            }
            weekMarketVOS = new ArrayList<>(map.values());
        }

        // 获取当前时间为第几周
        Date date = new Date();
        int week = DateUtils.getWhichWeek(DateUtils.convertToLocalDate(date));

        List<WeekMarketVO> sortedPeople = weekMarketVOS.stream()
                .sorted(Comparator.comparingInt(WeekMarketVO::getWeek))
                .collect(Collectors.toList());

        // 累加
        AtomicInteger cumulativeValue = new AtomicInteger(0);
        sortedPeople.stream().forEach(item -> {
            if (item.getWeek() <= week) {
                int i = cumulativeValue.get() + item.getMarketCount();
                cumulativeValue.set(i);
                item.setMarketCount(i);
            }
        });

        return sortedPeople;
    }

    /**
     * 根据时间段获取销售详情
     * @param marketInfoDTO
     * @return
     */
    @Override
    public SaleMarketInfoVO marketInfo(MarketInfoDTO marketInfoDTO) {
        // 根据时间段获取销售情况
        if (Objects.isNull(marketInfoDTO) || CollUtil.isEmpty(marketInfoDTO.getMachineIds())) {
            return null;
        }
        SaleMarketInfoVO saleMarketInfoVO = orderListService.marketInfo(marketInfoDTO);
        return saleMarketInfoVO;
    }

    /**
     * 获取销售订单列表
     * @param marketInfoDTO
     * @return
     */
    @Override
    public List<OrderMarketVO> marketList(MarketInfoDTO marketInfoDTO) {
        if (Objects.isNull(marketInfoDTO) || CollUtil.isEmpty(marketInfoDTO.getMachineIds())) {
            return new ArrayList<>();
        }
        List<OrderMarketVO> orderMarketVOList = orderListService.payOkOrderList(marketInfoDTO);
        return orderMarketVOList;
    }


    /**
     * 获取投资的设备id
     * @return
     */
    public List<String> getAllMachineIds(){
        Long userId = SecurityUtils.getUserId();
        List<MachineDO> machineInvestorByUserId = machineService.getMachineInvestorByUserId(userId);
        List<String> machineIds = machineInvestorByUserId.stream().map(MachineDO::getMachineId).collect(Collectors.toList());
        return machineIds;
    }

}
